package com.codebase.zookeeper.zk;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 删除一个节点和更新节点相似
 */
public class DeleteNode implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static ZooKeeper zk;

    @Override
    public void process(WatchedEvent event) {
        if(Event.KeeperState.SyncConnected == event.getState()){
            if(Event.EventType.None == event.getType() && null == event.getPath()){
                   countDownLatch.countDown();
            }
        }
    }

    /***
     * 同步删除节点
     */
    @Test
    public void test() throws Exception{
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new DeleteNode());
        String path = "/root";
        zk.create(path, "111".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Stat stat = zk.exists(path, true);
        if(stat != null){
            zk.delete(path, -1);
        }
    }

    /***
     * 异步删除节点
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        zk = new ZooKeeper("127.0.0.1:2181", 5000, new DeleteNode());
        String path = "/root";
        zk.create(path, "111".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Stat stat = zk.exists(path, true);
        if(stat != null){
            zk.delete(path, -1, new DeleteCallBaclk(), "ctx");
        }
        Thread.sleep(1000);
    }

    class DeleteCallBaclk implements AsyncCallback.VoidCallback{
        @Override
        public void processResult(int rc, String path, Object ctx) {
            System.out.println("rc:"+ rc);
            System.out.println("path:" + path);
            System.out.println("ctx:" + ctx);
        }
    }
    
}
